var jkMsgStore = new (function(){
	var _tabs = {};
	this.processMessages = function(tabid, data) {
		if(!data){
			return;
		}
		var tabdata = _tabs[tabid];
		if(!tabdata){
			tabdata = {
				comments:{},
				msgs:{},
				news:[]
			};
		}
		tabdata['title'] = data.title; 
		$.each(data.stream, function(idx, item) {
			if (item.comment_id) {
				if(!tabdata.comments[item.comment_id]){
					tabdata.comments[item.comment_id] = item;
					tabdata.news.push(item);
				}
			} else {
				if(!tabdata.msgs[item.id]){
					tabdata.msgs[item.id] = item;
					tabdata.news.push(item);
				}
			}
		});
		_tabs[tabid] = tabdata;
	}
});
var jaikuapi = new (function() {
	var JAIKU_DN = "jaiku.com";
	this.JK_API_SEND_END_POINT = "http://api." + JAIKU_DN + "/json";
	var JK_PERSONAL_END_POINT_BASE = "http://%USERNAME%." + JAIKU_DN
			+ "/feed/json";
	var JK_CONTACTS_END_POINT_BASE = "http://%USERNAME%." + JAIKU_DN
			+ "/contacts/feed/json";
	var JK_PUBLIC_END_POINT = "http://jaiku.com/feed/json";
	this.JK_TYPE_CONTACTS = 0;
	this.JK_TYPE_PERSONAL = 1;
	this.JK_TYPE_PUBLIC = 2;

	this.username = "";
	this.apikey = "";
	this.deflocation = "";
	this.personalURL = "";
	this.contactsURL = "";
	this.publicURL = JK_PUBLIC_END_POINT;
	this.updateInterval = 60;
	this.timerId = -1;

	this.send = function(msg, icon, location, generated, callback, errorhandler) {
		if (!msg) {
			return;
		}
		var data = {
			'user' : this.username,
			'personal_key' : this.apikey,
			'method' : 'presence.send',
			'location' : ''
		}
		data.message = msg;
		if (icon) {
			data.icon = icon
		}
		if (location) {
			data.location = location
		}
		if (isDef(generated)) {
			data.generated = generated;
		}
		if (!isDef(callback)) {
			callback = processSendResponse;
		}
		$.ajax(jaikuapi.JK_API_SEND_END_POINT, data, callback, 'json');
	};
	this.loadPrefs = function() {
		var prefsService = Components.classes["@mozilla.org/preferences-service;1"]
				.getService(Components.interfaces.nsIPrefService);
		var prefs = prefsService.getBranch(JK_PREFERENCE_BRANCH);

		this.username = prefs.getCharPref("username");
		this.apikey = prefs.getCharPref("api.key");
		this.deflocation = prefs.getCharPref("default.location");
		this.personalURL = JK_PERSONAL_END_POINT_BASE.replace(/%USERNAME%/,
				this.username);
		this.contactsURL = JK_CONTACTS_END_POINT_BASE.replace(/%USERNAME%/,
				this.username);
		this.updateInterval = prefs.getIntPref("refresh.interval");
		jk_logger.debug("default loc:" + this.deflocation);
		jk_logger.debug("personalURL:" + this.personalURL);
		jk_logger.debug("contactsURL:" + this.contactsURL);
		jk_logger.debug("publicURL:" + this.publicURL);
		jk_logger.debug("update interval:" + this.updateInterval);
		// update presence in 5 secs
		this.startAutoRefresh();
	};
	this.startAutoRefresh = function() {
		if (jaikuapi.updateInterval > 0) {
			if (jaikuapi.timerId != -1) {
				// clear last timeout id
				window.clearTimeout(jaikuapi.timerId);
				jaikuapi.timerId = window.setTimeout(
						"jaikuapi.refreshPresence(0)", jaikuapi.updateInterval
								* 1000);
				jk_logger.debug("set next update: " + jaikuapi.updateInterval
						* 1000)
			} else {
				jaikuapi.refreshPresence(0, function(data) {
					jaikuapi.timerId = 0; // prevent loop
					processPresence(data);
					jaikuapi.startAutoRefresh();
				});
			}
		}
	}
	this.refreshPresence = function(type, callback, tabid) {
		var url = this.publicURL;
		switch (type) {
			case jaikuapi.JK_TYPE_PERSONAL :
				url = this.personalURL;
				break;
			case jaikuapi.JK_TYPE_CONTACTS :
				url = this.contactsURL;
				break;
			case jaikuapi.JK_TYPE_PUBLIC :
			default :
				url = this.publicURL;
				break;
		}
		var data = {
			'user' : this.username,
			'personal_key' : this.apikey
		}
		jk_logger.debug("sending request..." + new Date());
		jQuery.getJSON(url, data, createCallback(callback, tabid));
	};

	function processSendResponse(data) {
		jk_logger.debug(data.toSource());
	};
	function createCallback(callback, tabid){
		if (!isDef(callback)) {
			return function(data){
				processPresence(tabid, data);
			}
		}else{
			return function(data){
				processPresence(tabid, data);
				callback(tabid, data);
			}
		}
	}
	function processPresence(tabid, data) {
		jkMsgStore.processMessages(tabid, data);
		//TODO: notify UI for update
	};
})();
